/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.common.sign;


import com.xiongyingqi.util.Assert;
import com.xiongyingqi.util.CollectionUtils;
import com.xiongyingqi.util.MD5Helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Sign utils.
 *
 * @author blademainer
 * @version 2016-08-21 00:25
 */
public abstract class SignUtils {
  private static final Logger LOGGER = LoggerFactory.getLogger(SignUtils.class);

  /**
   * Sign the params to md5 message.
   * @param params to signed parameters.
   * @param unsignedKeys keys that not join the sign params.
   * @param charset charset of md5.
   * @return md5(upper case)
   */
  public static String sign(Map<String, String> params, Set<String> unsignedKeys, String
      charset) {
    Assert.notEmpty(params, "parameters is null!");

    SortedMap<String, String> sortedMap = convertToSignMap(params, unsignedKeys);
    String signString = toSignString(sortedMap);
    String md5 = md5(signString, charset);
    return md5;
  }

  public static SortedMap<String, String> convertToSignMap(Map<String, String> params, Set<String>
      unsignedKeys) {
    Assert.notEmpty(params, "parameters is null!");

    SortedMap<String, String> sortedMap = new TreeMap<>();
    sortedMap.putAll(params);
    if (CollectionUtils.isEmpty(unsignedKeys)) {
      return sortedMap;
    }
    for (String unsignedKey : unsignedKeys) {
      String removed = sortedMap.remove(unsignedKey);
      LOGGER.debug("Removed unsigned key: '{}' with value: {}", unsignedKey, removed);
    }
    return sortedMap;
  }

  public static String toSignString(SortedMap<String, String> params) {
    Assert.notEmpty(params, "parameters is null!");
    StringBuilder builder = new StringBuilder();
    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
    for (; iterator.hasNext(); ) {
      Map.Entry<String, String> entry = iterator.next();
      builder.append(entry.getKey())
          .append("=")
          .append(entry.getValue());
      if (iterator.hasNext()) {
        builder.append("&");
      }
    }
    String signMessage = builder.toString();
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Returning sign string: \"{}\" by params: {}", signMessage, params);
    }
    return signMessage;
  }

  public static String md5(String signString, String charset) {
    Assert.hasText(signString, "Origin sign is null!");
    String md5 = MD5Helper.encrypt(signString, charset, true);
    LOGGER.debug("Returning md5: {} by sign string: {}", md5, signString);
    return md5;
  }
}
